/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

// xmls
var songxml,
artistxml,
albumxml,
playlistxml;
// results
var songrs,
artistrs,
albumrs,
playlistrs,
lyricsrs;
// general
var str,
contextPath;
// elements
var hotitem = "hot_item",
middlecontent="middle_content",
artistresult="artist_result",
albumresult="album_result",
songresult="song_result",
mvresult="MV_result",
lyricsresult="lyrics_result",
previewAudio = "previewAudio";
// class
var ulcss="list_content",
licss="item",
imgcss="item_img",
headercss="list_content_header_search",
firsttitle="first_title",
secondtitle = "second_title",
hlicss="horizontal_item",
topulcss="top_content";

//-------------------------------------------------------------
//-------------------------CONTROLLER--------------------------
//-------------------------------------------------------------
function ExecuteSearchOnPage(context,query){
    str = query;
    contextPath = context;

    // parse 4 xmls to doms
    xml = localStorage.getItem("songxml");
    songxml = new DOMParser().parseFromString(xml,"text/xml");
    xml = localStorage.getItem("artistxml");
    artistxml = new DOMParser().parseFromString(xml,"text/xml");
    xml = localStorage.getItem("albumxml");
    albumxml = new DOMParser().parseFromString(xml,"text/xml");
    xml = localStorage.getItem("playlistxml");
    playlistxml = new DOMParser().parseFromString(xml,"text/xml");
    xml = localStorage.getItem("historyxml");
    historyxml = new DOMParser().parseFromString(xml,"text/xml");

    SearchProcess();
}

function SearchProcess(){
    var tmp = str.VNize().removeAccent().toUpperCase();

    // start to search
    SearchInSongXML(tmp);
    SearchInArtistXML(tmp);
    SearchInAlbumXML(tmp);
    SearchInLyricsXML(tmp);
    // done search, keep progress display
    DisplayResult();
}

function DisplayResult(){

    RemoveResult();
    // show the closet result matches with query
    // 1. find it is in album,songs or artists
    // 2. get the one with top views.
    // 3. display it based on their type.
    DisplayTopItem();

    // Display artist found.
    DisplayArtist();

    // Display album found.
    DisplayAlbum();
    
    // Display mv found.
    DisplayMV();

    // Display song found.
    DisplaySong();

    // Display lyrics found
    DisplayLyrics();
}
//-------------------------------------------------------------
//---------------------------SEARCH----------------------------
//-------------------------------------------------------------

function SearchInSongXML(tmp){
    // variables
    songrs = [];
    // start
    var songs = songxml.getElementsByTagName("Song"); // <Song>
    var songhistory = historyxml.getElementsByTagName("Song");
    
    for(i=0;i<songs.length;i++){
        // Title
        var title = songs[i].getElementsByTagName("SongTitle")[0].firstChild.nodeValue;
        var comparison = title.VNize().removeAccent().toUpperCase();

        if(comparison.indexOf(tmp)>-1){
            var id = songs[i].getElementsByTagName("SongID")[0].firstChild.nodeValue;
            for(var j=0;j<songhistory.length;j++){
                var tmpid = songhistory[j].getElementsByTagName("SongID")[0].firstChild.nodeValue;
                if(tmpid==id){
                    var views = songhistory[j].getElementsByTagName("Views")[0].firstChild.nodeValue;
                    break;
                }else{
                    var views = 0;
                }
            }
            var isMV = songs[i].getElementsByTagName("isMV")[0].firstChild.nodeValue;
            var likeNumber = songs[i].getElementsByTagName("LikeNumber")[0].firstChild.nodeValue;
            var albumName;
            var albumID;
            if(songs[i].getElementsByTagName("AlbumTitle")[0].firstChild!=null){
                albumName = songs[i].getElementsByTagName("AlbumTitle")[0].firstChild.nodeValue;
                albumID = songs[i].getElementsByTagName("AlbumID")[0].firstChild.nodeValue;
            }else{
                albumName = "";
                albumID = "";
            }
            var src = songs[i].getElementsByTagName("SongSRC")[0].firstChild.nodeValue;
            var lyrics = songs[i].getElementsByTagName("Lyrics")[0].firstChild.nodeValue;
            // get percentage and index
            var per = getPercentageMatch(tmp, comparison);
            // Artist
            var artists = songs[i].getElementsByTagName("Artist");
            var artist = [];
            var artistList = [];
            for(j=0;j<artists.length;j++){
                var artistId = artists[j].getElementsByTagName("ArtistID")[0].firstChild.nodeValue;
                var artistName = artists[j].getElementsByTagName("ArtistName")[0].firstChild.nodeValue;

                artist.push({
                    artistId:artistId,
                    artistName:artistName
                });

                artistList.push({
                    artist:artist
                });
            }
            // add song to list
            songrs.push({
                id:id,
                isMV:isMV,
                title:title,
                views:views,
                albumName:albumName,
                albumID:albumID,
                src:src,
                lyrics:lyrics,
                likeNumber:likeNumber,
                artistList:artistList,
                per:per
            });
        } // end comparison
    }
    songrs = sortByViews(songrs);
}

function SearchInArtistXML(tmp){
    artistrs = [];

    var artists = artistxml.getElementsByTagName("Artist"); // <Song>
    var artisthistory = historyxml.getElementsByTagName("Artist");
    for(i=0;i<artists.length;i++){
        // Title
        var name = artists[i].getElementsByTagName("ArtistName")[0].firstChild.nodeValue;
        // var comparison = name.toUpperCase().VNize().removeAccent();
        var comparison = name.VNize().removeAccent().toUpperCase();

        if(comparison.indexOf(tmp)>-1){
            var id = artists[i].getAttribute("ArtistID");
            for(var j=0;j<artisthistory.length;j++){
                var tmpid = artisthistory[j].getElementsByTagName("ArtistID")[0].firstChild.nodeValue;
                if(tmpid==id){
                    var views = artisthistory[j].getElementsByTagName("Views")[0].firstChild.nodeValue;
                    break;
                }else{
                    var views = 0;
                }
            }
            var src = artists[i].getElementsByTagName("ArtistImageSRC")[0].firstChild;
            if(src!=null){
                src = artists[i].getElementsByTagName("ArtistImageSRC")[0].firstChild.nodeValue;
            }else{
                src = "ArtistDefault.jpg"; // set default image src
            }
            var biology = artists[i].getElementsByTagName("Biology")[0].firstChild.nodeValue;
            var subscribe = artists[i].getElementsByTagName("SubscriberNumber")[0].firstChild.nodeValue;
            // get percentage and index
            var per = getPercentageMatch(tmp, comparison);

            artistrs.push({
                id:id,
                name:name,
                src:src,
                views:views,
                subscribe:subscribe,
                biology:biology,
                per:per
            });
        } // end comparison
    }

    artistrs = sortByViews(artistrs);
}

function SearchInAlbumXML(tmp){
    albumrs = [];

    var albums = albumxml.getElementsByTagName("Album"); // <Song>
    var albumshistory = historyxml.getElementsByTagName("Album");
    for(var i=0;i<albums.length;i++){
        // Title
        var title = albums[i].getElementsByTagName("AlbumTitle")[0].firstChild.nodeValue;
        // var comparison = name.toUpperCase().VNize().removeAccent();
        var comparison = title.VNize().removeAccent().toUpperCase();

        if(comparison.indexOf(tmp)>-1){
            var songList = [];
            var id = albums[i].getElementsByTagName("AlbumID")[0].firstChild.nodeValue;
            for(var j=0;j<albumshistory.length;j++){
                var tmpid = albumshistory[j].getElementsByTagName("AlbumID")[0].firstChild.nodeValue;
                if(tmpid==id){
                    var views = albumshistory[j].getElementsByTagName("Views")[0].firstChild.nodeValue;
                    break;
                }else{
                    var views = 0;
                }
            }
            var src = albums[i].getElementsByTagName("AlbumCoverSRC")[0].firstChild.nodeValue;
            var artistName = albums[i].getElementsByTagName("ArtistName")[0].firstChild.nodeValue;
            var artistId = albums[i].getElementsByTagName("ArtistID")[0].firstChild.nodeValue;
            var desc = "";
            if(albums[i].getElementsByTagName("AlbumDescription")[0].firstChild!=null){
                desc = albums[i].getElementsByTagName("AlbumDescription")[0].firstChild.nodeValue;
            }
            var songs = albums[i].getElementsByTagName("Song");
            // get percentage and index
            var per = getPercentageMatch(tmp, comparison);

            for(j=0;j<songs.length;j++){
                var songsrc =songs[j].getElementsByTagName("SongSRC")[0].firstChild.nodeValue;

                songList.push({
                    songsrc:songsrc
                });
            }
            albumrs.push({
                id:id,
                artistName:artistName,
                artistId:artistId,
                src:src,
                views:views,
                title:title,
                desc:desc,
                songs:songList,
                per:per
            });
        } // end comparison
    }
    albumrs = sortByViews(albumrs);
}

function SearchInLyricsXML(tmp){
    var songs = songxml.getElementsByTagName("Song");
    var found = false;
    lyricsrs = [];

    if(tmp.length<4){
        return;
    }
    
    var sntmatches;
    for(var i=0;i<songs.length;i++){
        var lyrics = songs[i].getElementsByTagName("Lyrics")[0].firstChild.nodeValue;
        // cắt câu
        var sentences = seperateSentences(lyrics);
        sntmatches = [];
        for(var j=0;j<sentences.length;j++){
            var tmpS = sentences[j].VNize().removeAccent().toUpperCase();
            if(tmpS.indexOf(tmp)>-1){
                // song title, id
                var title = songs[i].getElementsByTagName("SongTitle")[0].firstChild.nodeValue;
                var id = songs[i].getElementsByTagName("SongID")[0].firstChild.nodeValue;
                // get start index
                var index = tmpS.indexOf(tmp);
                var processed = emphasizedWord(sentences[j].trim(), index-1,str);
                // sentences matched
                sntmatches.push(processed);
                found = true;
            }
        } // end for trong list cac cau
        if(found==true){
            lyricsrs.push({
                id:id,
                title:title,
                sentences:sntmatches
            });
            found = false;
        } // end check found
    } // end a song item
}

//-------------------------------------------------------------
//---------------------------DISPLAY----------------------------
//-------------------------------------------------------------

function DisplayArtist(){
    var output="";
    var maxLength=8;

    if(artistrs.length == 0){
        document.getElementById(artistresult).innerHTML = output;
        return;
    }else if(artistrs.length < maxLength){
        maxLength = artistrs.length;
    }

    output+="<ul class='"+ulcss+"'>";
    output+="<div class='"+headercss+"'>Nghệ Sỹ</div>";
    for(var i=0;i<maxLength;i++){
        output+= displayArtistItem(artistrs[i], contextPath);
    }
    output+="</ul>";

    document.getElementById(artistresult).innerHTML = output;
}

function DisplayAlbum(){
    var output="";
    var maxLength=8;
    albumrs = sortByViews(albumrs);

    if(albumrs.length == 0){
        document.getElementById(albumresult).innerHTML = output;
        return;
    }else if(albumrs.length < maxLength){
        maxLength = albumrs.length;
    }

    output+="<ul class='"+ulcss+"'>";
    output+="<div class='"+headercss+"'>Album</div>"
    for(var i=0;i<maxLength;i++){
        output+=displayAlbumItem(albumrs[i], contextPath);
    }
    output+="</ul>";

    document.getElementById(albumresult).innerHTML = output;
}

function DisplaySong(){
    var output="";
    var maxLength=8;
    songrs = sortByViews(songrs);

    if(songrs.length == 0){
        document.getElementById(songresult).innerHTML = output;
        return;
    }else if(songrs.length < maxLength){
        maxLength = songrs.length;
    }

    output+="<ul class='"+ulcss+"'>";
    output+="<div class='"+headercss+"'>Bài Hát</div>"
    for(var i=0;i<maxLength;i++){
        if(songrs[i].isMV=="false"){
            output+=displaySongItem(songrs[i], i);
        }
    }
    output+="</ul>";

    document.getElementById(songresult).innerHTML = output;
}

function DisplayLyrics(){
    var output="";
    var maxLength=8;

    if(typeof(lyricsrs)=='undefined'){
        document.getElementById(lyricsresult).innerHTML = output;
        return;
    }

    if(lyricsrs.length == 0){
        document.getElementById(lyricsresult).innerHTML = output;
        return;
    }else if(lyricsrs.length < maxLength){
        maxLength = lyricsrs.length;
    }

    output+="<ul class='"+ulcss+"'>";
    output+="<div class='"+headercss+"'>Lyrics</div>"
    for(var i=0;i<maxLength;i++){
        // output
        output+=displayLyricsItem(lyricsrs[i]);
    }
    output+="</ul>";

    document.getElementById(lyricsresult).innerHTML = output;
}

function DisplayMV(){
    var output="";
    var mvout="";
    var maxLength=8;
    songrs = sortByViews(songrs);

    if(songrs.length == 0){
        document.getElementById(mvresult).innerHTML = output;
        return;
    }else if(songrs.length < maxLength){
        maxLength = songrs.length;
    }

    for(var i=0;i<maxLength;i++){
        if(songrs[i].isMV == "true"){
            // output
            mvout+=displayMVItem(songrs[i]);
        }
    }

    if(mvout!=""){
        output+="<ul class='"+ulcss+"'>";
        output+="<div class='"+headercss+"'>MV</div>";
        output+=mvout;
        output+="</ul>";
    }
    
    document.getElementById(mvresult).innerHTML = output;
}

function DisplayTopItem(){
    // local variable
    var type=-1,output="",
    art=0,son=0,alb=0,
    sid,atid,alid;

    // 0 is lyrics, 1 is artist, 2 is album, 3 is song
    if(str>=10){
        type=0;
    }else{
        // tim item giong chuoi tim nhat trong tung rs
        sid = findTopFitItem(songrs);
        atid = findTopFitItem(artistrs);
        alid = findTopFitItem(albumrs);

        if(sid!=-1){
            son=songrs[sid].per;
        }
        if(atid!=-1){
            art = artistrs[atid].per;
        }
        if(alid!=-1){
            alb = albumrs[alid].per;
        }
        type = findMax(art, alb, son);
    } // end truong hop string query nho hon 10

    // control display by type.
    output+="<ul class='"+topulcss+"'>";
    if(type==0){
        if(lyricsrs.length==0){
            output+=displayNoneItem(str);
        }else{
            output+=displayTopAsLyricsItem(lyricsrs.splice(0,1));
        }
    }
    if(type==1){
        output+=displayTopAsArtistItem(artistrs.splice(atid,1)[0], contextPath);
    }
    if(type==2){
        output+=displayTopAsAlbumItem(albumrs.splice(alid,1)[0], contextPath);
    }
    if(type==3){
        output+=displayTopAsSongItem(songrs.splice(sid, 1)[0], contextPath);
    }
    output+="</ul>";

    document.getElementById(hotitem).innerHTML = output;

} // end

//-------------------------------------------------------------
//------------------------------UTIL---------------------------------
//-------------------------------------------------------------

function playPreview(index){
    var audios = document.getElementsByName(previewAudio);
    var btn = document.getElementsByName("preview_button");
    var src = getSongSRC(songrs[index]);

    if(audios[index].currentTime==0){
        audios[index].src = src;
    }
    //Tests the paused attribute and set state.
    if (audios[index].paused) {
        for(var i=0;i<btn.length;i++){
            if(btn[i].textContent=="Pause"){
                btn[i].textContent = "Preview";
                audios[i].pause();
            }
        }
        audios[index].play();
        btn[index].textContent = "Pause";
    }
    else {
        audios[index].pause();
        btn[index].textContent = "Preview";
    }
}

function getSongSRC(des){
    var artist="";
    var album="";
    var song="";
    var src="";
    var albums = albumxml.getElementsByTagName("Album");
    for(var i = 0;i<albums.length;i++){
        var title = albums[i].getElementsByTagName("AlbumTitle")[0].firstChild.nodeValue;
        if(title.trim().toUpperCase()==
            des.albumName.trim().toUpperCase()){
            artist = albums[i].getElementsByTagName("ArtistName")[0].firstChild.nodeValue;
            album = title.trim();
            song = des.src.trim();
        }
    }

    if(artist!="" && album!="" && song!=""){
        src = contextPath + "/db/" + artist + "/Album/" + album + "/" + song+".mp3";
    }

    return src;
}

function getPercentageMatch(tar,des){
    return Math.round((tar.length/des.length)*100);
}

function RemoveResult(){
    var mainDiv = document.getElementById(middlecontent);
    var divs = mainDiv.getElementsByTagName("div");

    for(var i=0;i<divs.length;i++){
        var uls = divs[i].getElementsByTagName("UL");
        for(var j=0;j<uls.length;j++){
            divs[i].removeChild(uls[j]);
        }
    }
}

function getMVSRC(des){
    var artist=des.artistList[0].artist[0].artistName.trim();
    var src="";
    var mv=des.src.trim();

    if(artist!="" && mv!=""){
        src = contextPath + "/db/" + artist + "/MV/" + mv +".webm";
    }

    return src;
}

function getCapture(des){
    var artist=des.artistList[0].artist[0].artistName.trim();
    var src="";
    var ss=des.src.trim();
    
    if(artist!="" && ss!=""){
        src = contextPath + "/db/" + artist + "/MV/" + ss +".jpg";
    }

    return src;
}